package com.yz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yz.common.R;
import com.yz.entity.AddressBook;
import com.yz.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新建用户收货地址
     * @param addressBook
     * @param session
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook, HttpSession session){
        log.info("AddressBook:{}", addressBook);

        Long userId = (Long) session.getAttribute("user");

        // 设置默认数据
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);

        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    /**
     * 获取用户地址数据列表
     * @param session
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(HttpSession session){
        // 获取Session中保存的用户id
        Long userId = (Long) session.getAttribute("user");
        // 根据用户id查询address_book表 获取用户的地址数据列表
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, userId);
        List<AddressBook> list = addressBookService.list(wrapper);
        return R.success(list);
    }

    /**
     * 设置默认地址
     * @param id
     * @return
     */
    @PutMapping("/default")
    public R<String> setDefault(Long id,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        // 把用户所有的地址设为非默认
        wrapper.eq(AddressBook::getUserId,userId);
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(0);
        addressBookService.update(addressBook,wrapper);
        // 把选中的地址设置为默认
        wrapper.eq(AddressBook::getId,id);
        addressBook.setIsDefault(1);
        addressBookService.update(addressBook,wrapper);
        return R.success("设置成功");
    }

    /**
     * 获取默认地址
     * @param session
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> getDefault(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,userId);
        AddressBook one = addressBookService.getOne(wrapper);
        return R.success(one);
    }
}
